﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HostAssistantCore
{
    public class IISManager
    {
        private static AddSiteUtil addsiteUtil = new AddSiteUtil();//创建添加站点工具
        private IUtil util = UtilFactory.GetUtil();//创建工厂


        public int Manager(string[] args, SiteInfo siteinfo)
        {
            int errorCode = ErrorCode.Succeed;
            try
            {
                if (args.Length <= 1)
                {
                    errorCode = ErrorCode.InvalidParameter;
                    Console.WriteLine("Invalid Parameters.");
                }
                else
                {
                    if (util != null)
                    {
                        switch (args[0].ToUpper())
                        {
                            //新建站点 
                            case "CREATESITE":
                                errorCode = CreateSite(util, siteinfo);
                                break;
                            case "RCREATESITE":
                                errorCode = R_CreateSite(util, siteinfo);
                                break;
                            case "SETSITE":
                                errorCode = SetSite(util, siteinfo);
                                break;
                            //移除站点
                            case "REMOVESITE":
                                errorCode = RemoveSite(util, args);
                                break;

                            //新建应用程序池
                            case "CREATEAPPPOOL":
                                errorCode = CreateAppPool(util, args);
                                break;

                            //移除应用程序池
                            case "REMOVEAPPPOOL":
                                errorCode = RemoveAppPool(util, args);
                                break;

                            //新建虚拟目录
                            case "CREATEDIR":
                                errorCode = CreateDir(util, args);
                                break;

                            //移除虚拟目录
                            case "REMOVEDIR":
                                errorCode = RemoveDir(util, args);
                                break;

                            //创建应用程序
                            case "CREATEAPP":
                                errorCode = CreateApp(util, args);
                                break;

                            //移除应用程序
                            case "REMOVEAPP":
                                errorCode = RemoveApp(util, args);
                                break;

                            //站点是否存在
                            case "SITEEXIST":
                                errorCode = SiteExist(util, args);
                                break;

                            //变更站点证书
                            case "SETCERT":
                                errorCode = SetCertificate(util, args);
                                break;

                            //变更站点端口
                            case "SETPORT":
                                errorCode = SetPort(util, args);
                                break;
                            case "REMOVEFTP":
                                errorCode = RemoveFtp(util, args);
                                break;
                            case "ADDREWRITE":
                                errorCode = CreateRewriteRule(args[0], args[1]);
                                break;
                        }
                    }
                    else
                    {
                        //IIS版本未知
                        errorCode = ErrorCode.UnknownIISVer;
                    }
                }
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                errorCode = ErrorCode.Unknown;
            }

            return errorCode;
        }
      
        
        
        /// <summary>
        /// 获取系统环境
        /// </summary>
        /// <returns></returns>
        public string getSysInfo()
        {
            IISInfoUtil infoutil = new IISInfoUtil();
            return infoutil.geInfo();
        }

        /// <summary>
        /// 从参数中取指定值
        /// </summary>
        /// <param name="args"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        private static string GetValue(string[] args, string key)
        {
            string value = string.Empty;

            foreach (string p in args)
            {
                string prefix = string.Format("/{0}:", key);
                if (p.StartWithEx(prefix) && p.Length > prefix.Length)
                {
                    value = p.Substring(prefix.Length);
                }
            }

            return value;
        }
        /// <summary>
        /// 创建站点
        /// </summary>
        /// <param name="util"></param>
        /// <param name="siteinfo"></param>
        /// <returns></returns>
        private static int CreateSite(IUtil util, SiteInfo siteinfo)
        {
            int errorCode = ErrorCode.Succeed;
              
            errorCode = util.CreateSite(siteinfo);

            return errorCode;
        }

        private static int R_CreateSite(IUtil util, SiteInfo siteinfo)
        {
            int errorCode = ErrorCode.Succeed;

            errorCode = util.R_CreateSite(siteinfo);

            return errorCode;
        }

        private static int RemoveSite(IUtil util, string[] args)
        {
            int errorCode = ErrorCode.Succeed;
            string siteName = args[1];

            //必须指定站点名
            if (siteName.IsNullOrEmpty())
                errorCode = ErrorCode.InvalidParameter;
            else
                errorCode = util.RemoveSite(siteName);

            return errorCode;
        }

        private static int CreateAppPool(IUtil util, string[] args)
        {
            int errorCode = ErrorCode.Succeed;
            string poolName = GetValue(args, "poolName");

            //必须指定池名称
            if (poolName.IsNullOrEmpty())
                errorCode = ErrorCode.InvalidParameter;
            else
                errorCode = util.CreateAppPool(poolName);

            return errorCode;
        }
        /*
         * 删除应用池
         */
        private static int RemoveAppPool(IUtil util, string[] args)
        {
            int errorCode = ErrorCode.Succeed;
            string poolName = args[1];

            //必须指定池名称
            if (poolName.IsNullOrEmpty())
                errorCode = ErrorCode.InvalidParameter;
            else
                errorCode = util.RemoveAppPool(poolName);

            return errorCode;
        }

        private static int CreateDir(IUtil util, string[] args)
        {
            int errorCode = ErrorCode.Succeed;
            string siteName = GetValue(args, "siteName");
            string virtualPath = GetValue(args, "virtualPath");
            string physicalPath = GetValue(args, "physicalPath");
            string enableAllMimeTypes = GetValue(args, "enableAllMimeTypes");

            //站点名、虚拟路径、物理路径不可为空
            if (siteName.IsNullOrEmpty() || virtualPath.IsNullOrEmpty() || physicalPath.IsNullOrEmpty())
                errorCode = ErrorCode.InvalidParameter;
            else
                errorCode = util.CreateDir(siteName,
                                    virtualPath,
                                    physicalPath,
                                    enableAllMimeTypes.IsNullOrEmpty() ? false : Convert.ToBoolean(enableAllMimeTypes)
                                );

            return errorCode;
        }

        private static int RemoveDir(IUtil util, string[] args)
        {
            int errorCode = ErrorCode.Succeed;
            string siteName = GetValue(args, "siteName");
            string virtualPath = GetValue(args, "virtualPath");

            //站点名、虚拟路径不可为空
            if (siteName.IsNullOrEmpty() || virtualPath.IsNullOrEmpty())
                errorCode = ErrorCode.InvalidParameter;
            else
                errorCode = util.RemoveDir(siteName, virtualPath);

            return errorCode;
        }

        private static int CreateApp(IUtil util, string[] args)
        {
            int errorCode = ErrorCode.Succeed;
            string siteName = GetValue(args, "siteName");
            string virtualPath = GetValue(args, "virtualPath");
            string physicalPath = GetValue(args, "physicalPath");
            string poolName = GetValue(args, "poolName");
            string useSsl = GetValue(args, "useSsl");

            //站点名、虚拟路径、物理路径、池名称不可为空
            if (siteName.IsNullOrEmpty() || virtualPath.IsNullOrEmpty() || physicalPath.IsNullOrEmpty())
                errorCode = ErrorCode.InvalidParameter;
            else
                errorCode = util.CreateApp(siteName,
                                    virtualPath,
                                    physicalPath,
                                    poolName,
                                    useSsl.IsNullOrEmpty() ? false : Convert.ToBoolean(useSsl)
                                );

            return errorCode;
        }

        private static int RemoveApp(IUtil util, string[] args)
        {
            int errorCode = ErrorCode.Succeed;
            string siteName = GetValue(args, "siteName");
            string virtualPath = GetValue(args, "virtualPath");

            //站点名、虚拟路径不可为空
            if (siteName.IsNullOrEmpty() || virtualPath.IsNullOrEmpty())
                errorCode = ErrorCode.InvalidParameter;
            else
                errorCode = util.RemoveApp(siteName, virtualPath);

            return errorCode;
        }

        private static int SiteExist(IUtil util, string[] args)
        {
            int errorCode = ErrorCode.Succeed;
            string siteName = GetValue(args, "siteName");

            //站点名不可为空
            if (siteName.IsNullOrEmpty())
                errorCode = ErrorCode.InvalidParameter;
            else
                errorCode = addsiteUtil.SiteExist("");

            return errorCode;
        }

        private static int RemoveFtp(IUtil util, string[] args)
        {
            int errorCode = ErrorCode.Succeed;

            if (!util.DeleteFtp(args[0]))
            {
                errorCode = ErrorCode.CommitFail;
            }

            return errorCode;
        }

        private static int SetCertificate(IUtil util, string[] args)
        {
            int errorCode = ErrorCode.Succeed;
            string siteName = GetValue(args, "siteName");
            string sslHash = GetValue(args, "sslHash");

            //站点名、证书hash不可为空
            if (siteName.IsNullOrEmpty() || sslHash.IsNullOrEmpty())
                errorCode = ErrorCode.InvalidParameter;
            else
                errorCode = util.SetCertificate(siteName, sslHash);

            return errorCode;
        }

        private static int SetPort(IUtil util, string[] args)
        {
            int errorCode = ErrorCode.Succeed;
            string siteName = GetValue(args, "siteName");
            string httpPort = GetValue(args, "httpPort");
            string httpsPort = GetValue(args, "httpsPort");

            //参数基本检查
            if (siteName.IsNullOrEmpty())										//站点名不可为空
                errorCode = ErrorCode.InvalidParameter;
            else if (httpPort.IsNullOrEmpty() && httpsPort.IsNullOrEmpty())		//两个端口号不可同时为空
                errorCode = ErrorCode.InvalidParameter;
            else
                errorCode = util.SetPort(siteName,
                                    httpPort.IsNullOrEmpty() ? 0 : Convert.ToInt32(httpPort),
                                    httpsPort.IsNullOrEmpty() ? 0 : Convert.ToInt32(httpsPort)
                                );

            return errorCode;
        }
        /// <summary>
        /// 获取数据库站点信息
        /// </summary>
        public List<Sites> getAdoSiteInfo()
        { 
             
            try
            {
                return IISAdoHelper.adoGetSitesInfo();
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                return null;
            }
        }
        /// <summary>
        /// 获取数据库站点信息用于生成配置文件
        /// </summary>
        public DataTable getAdoConfigSiteInfo()
        {
            try
            {
                return IISAdoHelper.adoGetConfigSitesInfo();
            }
            catch (Exception ex)
            {
                NLogger.Error("从数据库获取站点配置信息失败:" + ex.ToString());
                return null;
            }
        }
        /// <summary>
        /// 刷新站点数据
        /// </summary>
        public List<Sites> flushSites()
        {
            try
            {
                return IISAdoHelper.adoFlushSites();
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                return null;
            }
        }
        /// <summary>
        /// 获取FTP站点信息
        /// </summary>
        /// <returns></returns>
            public List<string> getFtpInfo()
        {
            try
            { 
                return util.GetFtpInfos();
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                throw ex;
                return null;
            }
        }
        /// <summary>
        /// 刷新FTP站点信息
        /// </summary>
        /// <returns></returns>
        public void flushFtps()
        { 
            try
            {
                 IISAdoHelper.adoFlushFtpInfos();
            }
            catch(Exception ex)
            {
                NLogger.Error(ex.ToString());
                throw ex;
               
            }
        }
        /// <summary>
        /// 获取站点信息
        /// </summary>
        public List<string> getSiteInfo()
        {
            try
            {
                return util.GetSiteInfo();
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                return null;
            }
        }
        /// <summary>
        /// 获取新站点信息
        /// </summary>
        public string getNewSiteInfo(string newsitename)
        {
            try   
            {
                return util.GetNewSiteInfo(newsitename);
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                return null;
            }
        }
        /// <summary>
        /// 编辑站点
        /// </summary>
        /// <param name="util"></param>
        /// <param name="siteinfo"></param>
        /// <returns></returns>
        public int SetSite(IUtil util, SiteInfo siteinfo)
        {
            int errorCode = ErrorCode.Succeed;

            errorCode = util.SetSite(siteinfo);

            return errorCode;
        }
        public bool DeleteSite(string deletesitename)
        {  
            try
            {
                IISAdoHelper.adoDeleteSite(deletesitename);
                return true;
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                return false;
            }
        }
        /// <summary>
        /// 获取站点路径
        /// </summary>
        /// <param name="util"></param>
        /// <param name="sitename"></param>
        /// <returns></returns>
        public string GetSitePath(string sitename)
        {
            return util.GetSitePath(sitename);
        }
        /// <summary>
        /// 获取所有站点路径
        /// </summary>
        /// <param name="util"></param>
        /// <param name="sitename"></param>
        /// <returns></returns>
        public List<string> GetSiteNames()
        {
            return util.GetSiteNames();
        }
        /// <summary>
        /// 删除FTP站点
        /// </summary>
        /// <returns></returns>
        public bool DeleteFtp(string ftpname)
        {
            return util.DeleteFtp(ftpname);
        }
        /// <summary>
        /// 创建FTP站点
        /// </summary>
        /// <param name="ftpname"></param>
        /// <param name="ftppass"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public int CreateFtp(string ftpname, string ftppass, string path)
        {    
            return util.CreateFtp(ftpname, ftppass, path);
        }

        public void CreateFtppor(bool rw, string ftpname)
        {
            new FtpUtil().SetFtpAccessnew(ftpname, rw);

          
        }

        public void PasswordChange(string account, string password)
        { 
             FtpUtil.PasswordChange( account,  password);


        }




        public int CreateFtp(bool rw, string ftpname, string ftppass, string path)
        {
          
            return util.CreateFtp(rw, ftpname, ftppass, path);
        }

        /// <summary>
        /// 创建Rewrite配置
        /// </summary>
        /// <param name="ftpname"></param>
        /// <param name="ftppass"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public int CreateRewriteRule(string sitename, string sitepath)
        {
            try
            {
                return util.CreateRewriteRule(sitename, sitepath);
            }
            catch
            {
                return ErrorCode.CommitFail;
            }

        }
        /// <summary>
        /// 删除站点用户
        /// </summary>
        /// <returns></returns>
        public int DeleteSiteUsers()
        {
            try
            {
                return util.DeleteSiteUsers();
            }
            catch
            {
                return ErrorCode.CommitFail;
            }
        }

        /// <summary>
        /// add redirect rule
        /// </summary>
        /// <returns></returns>
        public int HttpRedirectAdd(string source_url, string target_url, string sitename)
        {
            try
            {
                return util.HttpRedirectAdd(source_url, target_url, sitename);
            }
            catch
            {
                return ErrorCode.CommitFail;
            }
        }
    }
}
